<?php
/**
 * Created by PhpStorm.
 * User: mUsr
 * Date: 18/6/29
 * Time: 下午8:45
 */


class Storage
{
    static $shmDir = '/dev/shm';
    static $separator = ':';

    protected $baseDir;
    protected $mode;

    function __construct($tmpfs = null, $subdir = 'swoole', $mode = 0777) // 此处权限一定要设置成0777
    {
        if ($tmpfs) {
            $this->baseDir = $tmpfs . '/' . $subdir;
        } else {
            $this->baseDir = self::$shmDir . '/' . $subdir;
        }
        $this->mode = $mode;
        if (!is_dir($this->baseDir)) {
            mkdir($this->baseDir, $this->mode, true);
        }
    }

    protected function getFile($key, $createDir = false)
    {
        $file = $this->baseDir . '/' . str_replace(self::$separator, '/', trim($key, self::$separator));
        $dir = dirname($file);
        if ($createDir and !is_dir($dir)) {
            mkdir($dir, $this->mode, true);
        }
        return $file;
    }

    function get($key)
    {
        $file = $this->getFile($key);
        if (!is_file($file)) {
            return false;
        }
        $res = file_get_contents($file);
        if ($res) {
            return json_decode($res, true);
        } else {
            return false;
        }
    }

    function set($key, $value)
    {
        $file = $this->getFile($key, true);
        if (file_put_contents($file, json_encode($value), LOCK_EX) === false) {
            return false;
        } else {
            return true;
        }
    }

    function exists($key)
    {
        return is_file($this->getFile($key));
    }

    function scan($prefix)
    {
        $dir = $this->baseDir . '/' . str_replace(self::$separator, '/', trim($prefix, self::$separator));
        if (!is_dir($dir)) {
            return false;
        }
        return scandir($dir);
    }

    function del($key)
    {
        $file = $this->getFile($key);
        return unlink($file);
    }
}